package DButils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import DATA.User;
import org.apache.commons.dbcp2.*;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;

public class ConnectTool {
    private static BasicDataSource bds;
//    private static String  pwd="4396777gla";
    private static String  pwd="mysqlpassword";//鹅的密码
    {
        boolean res=DbUtils.loadDriver("com.mysql.cj.jdbc.Driver");
        if(!res){
            throw new RuntimeException("连接数据库失败");
        }
        bds=new BasicDataSource();
        bds.setDriverClassName("com.mysql.cj.jdbc.Driver");
//        bds.setUrl("jdbc:mysql://localhost:3306/BookCub?useUnicode=true&characterEncoding=UTF-8");
        bds.setUrl("jdbc:mysql://localhost:3306/BookCub?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");//好家伙现在还要设置时区了？
        bds.setUsername("root");
        bds.setPassword(pwd);
        bds.setInitialSize(10);
    }
    public Connection getConnection() throws SQLException {
        return bds.getConnection();
    }
    public void ConnectClose(Connection coon) throws SQLException {
        DbUtils.close(coon);
    }
    public void StateClose(Statement statement) throws SQLException {
        DbUtils.close(statement);
    }
    public void ResultCLose(ResultSet resultSet) throws SQLException {
        DbUtils.close(resultSet);
    }
    public Object find(String sql,ResultSetHandler<?> rsh,Object... params) throws SQLException {
        //丢连接，sql语句和new 一个BeanHandler进来获取查询结果【单个】，或者BeanListHandler【获取结果的list】
        QueryRunner queryRunner=new QueryRunner(bds);
        Object ans= queryRunner.query(sql,rsh ,params);
        return ans;
    }
    public boolean insert(String sql,ResultSetHandler<?> rsh,Object... params) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(bds);
        Object ans=queryRunner.insert(sql,rsh,params);
        return ans!=null;
    }
    public boolean update(String sql,Object...params) throws SQLException {
        QueryRunner queryRunner=new QueryRunner(bds);
        int ans=queryRunner.update(sql,params);
        return ans>0;
    }
}
